package woaini.wind.ai.controller;

import cn.hutool.core.collection.CollUtil;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.model.ollama.OllamaStreamingChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.spring.AiService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.http.MediaType.TEXT_EVENT_STREAM_VALUE;

/** This is an example of using an {@link AiService}, a high-level LangChain4j API. */
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AssistantController {

  private final AssistantService assistantService;

  private final AssistantTools assistantTools;

  @GetMapping(value = "/streamingAssistant", produces = TEXT_EVENT_STREAM_VALUE)
  public Flux<String> streamingAssistant(@RequestParam(value = "message") String message) {

    System.out.println(message);

    StreamingChatLanguageModel model =
        OllamaStreamingChatModel.builder()
            .baseUrl("http://10.8.1.250:11434")
            .modelName("qwq:latest")
            .listeners(CollUtil.newArrayList(new MyChatModelListener()))
            .logRequests(true)
            .logResponses(true)
            .build();

    StreamingAssistant aistreamingAssistant =
        AiServices.builder(StreamingAssistant.class)
            .streamingChatLanguageModel(model)
            //           .systemMessageProvider(s -> "你是一名温和的助手,语言环境是中文,你需要根据用户的问题作出回复")
            .chatMemory(MessageWindowChatMemory.withMaxMessages(10))
            .tools(assistantTools)
            .build();

    return aistreamingAssistant.chat(message);
  }

  @GetMapping(value = "/assistant")
  public AIResponse assistant(
      @RequestParam(value = "message") String message,
      @RequestParam(value = "id") Integer id,
      @RequestParam(required = false,defaultValue = "false") Boolean isNew) {
    return assistantService.assistant(message,id,isNew);
  }
}
